﻿using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System;
using System.IO;
using System.Text;

namespace KJSyncXP.Extensions
{
    public static class JsonSerializeHelper
    {
        /// <summary>
        /// 将对象序列化为JSON字符串（默认格式化）
        /// </summary>
        public static string SerializeObjectToJson(object source)
        {
            try
            {
                // Newtonsoft.Json默认序列化（默认带缩进）
                var serializeStr = JsonConvert.SerializeObject(source);
                return serializeStr;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 将对象序列化为JSON字符串（支持压缩配置）
        /// </summary>
        public static string SerializeObjectToJson(object source, bool compress)
        {
            try
            {
                // Newtonsoft.Json格式化配置：compress=true时无缩进，false时带缩进
                var settings = new JsonSerializerSettings
                {
                    Formatting = compress ? Formatting.None : Formatting.Indented
                };
                var serializeStr = JsonConvert.SerializeObject(source, settings);
                return serializeStr;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 将对象序列化为BSON格式（返回Base64编码字符串，便于传输存储）
        /// </summary>
        /*public static string SerializeObjectToBson(object source)
        {
            try
            {
                // Newtonsoft.Json原生支持BSON序列化
                using (var ms = new MemoryStream())
                using (var bsonWriter = new BsonWriter(ms))
                {
                    var serializer = new JsonSerializer();
                    serializer.Serialize(bsonWriter, source);
                    // BSON字节数组转Base64字符串返回
                    return Convert.ToBase64String(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw new Exception("BSON序列化失败", ex);
            }
        }*/

        /// <summary>
        /// 从JSON字符串反序列化为指定类型对象
        /// </summary>
        public static TTarget DeserializeObjectFromJson<TTarget>(string json)
        {
            try
            {
                if (json is null)
                {
                    return default(TTarget);
                }
                // Newtonsoft.Json反序列化JSON字符串
                return JsonConvert.DeserializeObject<TTarget>(json);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 从JSON文件反序列化为指定类型对象
        /// </summary>
        public static TTarget DeserializeObjectFromFile<TTarget>(string filePath)
        {
            try
            {
                // 先读取文件内容（默认UTF8编码），再反序列化
                string jsonContent = File.ReadAllText(filePath, Encoding.UTF8);
                return JsonConvert.DeserializeObject<TTarget>(jsonContent);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 从流（JSON格式）反序列化为指定类型对象
        /// </summary>
        /*public static TTarget DeserializeObjectFromStream<TTarget>(Stream stream)
        {
            try
            {
                stream.Position = 0; // 重置流位置到起始处
                // 读取流内容为UTF8字符串，再反序列化
                using (var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true))
                {
                    string jsonContent = reader.ReadToEnd();
                    return JsonConvert.DeserializeObject<TTarget>(jsonContent);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }*/

        /// <summary>
        /// 从Base64编码的BSON字符串反序列化为指定类型对象
        /// </summary>
        /*public static T DeserializeObjectFromBson<T>(string bsonBase64data)
        {
            try
            {
                if (string.IsNullOrEmpty(bsonBase64data))
                {
                    return default(T);
                }
                // Base64字符串转BSON字节数组
                byte[] bsonBytes = Convert.FromBase64String(bsonBase64data);
                // 从BSON字节数组反序列化
                using (var ms = new MemoryStream(bsonBytes))
                using (var bsonReader = new BsonReader(ms))
                {
                    var serializer = new JsonSerializer();
                    return serializer.Deserialize<T>(bsonReader);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("BSON反序列化失败", ex);
            }
        }*/

        /// <summary>
        /// 将对象序列化为JSON并写入文件
        /// </summary>
        public static string SerializeObjectToFile(object source, string fileName)
        {
            try
            {
                // 先序列化对象
                string serializeStr = JsonConvert.SerializeObject(source, Formatting.Indented);
                // 写入文件（默认UTF8编码，覆盖已有文件）
                File.WriteAllText(fileName, serializeStr, Encoding.UTF8);
                return serializeStr;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
